package com.bysc.userservice.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.utils.MD5;
import com.bysc.commonutils.vo.JoinUserDept;
import com.bysc.commonutils.vo.TitleVo;
import com.bysc.commonutils.vo.UserInfoVo;
import com.bysc.userservice.client.JoinClient;
import com.bysc.userservice.entity.UserInfo;
import com.bysc.userservice.entity.vo.LoginVo;
import com.bysc.userservice.entity.vo.RegisterVo;
import com.bysc.userservice.entity.vo.UserInfoQueryVo;
import com.bysc.userservice.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2024-05-20
 */
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/userservice/user-info")
public class UserInfoController {

    //private final ExecutorService executorService = new ThreadPoolExecutor(2,10,60,TimeUnit.MINUTES,new ArrayBlockingQueue(10)); // 可以根据需要选择线程池大小
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private JoinClient joinClient;
    @Autowired
    private UserTitleController userTitleController;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public Results login(@RequestBody LoginVo loginVo) {
        try {
            String token = userInfoService.login(loginVo);
            return Results.ok().data("token", token).message(MessageConstant.LOGIN_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        }catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.LOGIN_FAIL);

        }
    }


    @ApiOperation(value = "会员注册")

    @PostMapping("register")

    public Results register(@RequestBody RegisterVo registerVo) {
        try {
            userInfoService.register(registerVo);
            return Results.ok().message(MessageConstant.REGISTERED_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        }catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.REGISTERED_FAIL);
        }
    }


    @ApiOperation(value = "根据token获取用户基础信息")
    @GetMapping("getUserInfoByToken")
    public Results getLoginInfo(HttpServletRequest request) {
        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            //Future<Boolean> joinFuture = executorService.submit(() -> isJoin(memberId));

            // 从数据库获取用户信息
            UserInfo user = userInfoService.getById(memberId);
            Boolean join = isJoin(memberId);
            // 等待joinFuture完成
            //Boolean join = joinFuture.get();
            return Results.ok().data("user", user).data("isJoin", join).message(MessageConstant.QUERY_USERINFO_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USERINFO_FAIL);
        }
    }
    @ApiOperation(value = "根据id获取用户基础信息")
    @GetMapping("getUserBaseInfoById/{id}")
    public Results getUserBaseInfoById(@PathVariable String id) {
        try {
            // 从数据库获取用户信息
            UserInfo user = userInfoService.getById(id);
            Boolean join = isJoin(id);
            // 等待joinFuture完成
            //Boolean join = joinFuture.get();
            return Results.ok().data("user", user).data("isJoin", join).message(MessageConstant.QUERY_USERINFO_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USERINFO_FAIL);
        }
    }
    @ApiOperation(value = "根据用户id获取用户详细信息")
    @GetMapping("getUserInfoById/{id}")
    public Results getUserInfoById(@ApiParam(name = "id", value = "用户id", required = true)
                                   @PathVariable String id) {
        try {
            UserInfo userInfo = userInfoService.getById(id);
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo, userInfoVo);
            // 获取头衔信息
            ArrayList<TitleVo> titles = JSON.parseObject(JSON.toJSONString(userTitleController.getTitleById(id).getData().get("titles")), ArrayList.class);
            userInfoVo.setTitles(titles);
            // 获取是否为协会成员信息
            Boolean join = isJoin(id);
            userInfoVo.setIsJoin(join);
            //获取是否为活跃用户信息
            Boolean isActive = (Boolean) isDisabled(id).getData().get("isDisabled");
            userInfoVo.setIsActive(isActive);
            return Results.ok().data("user", userInfoVo).message(MessageConstant.QUERY_USERINFO_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USERINFO_FAIL);
        }
    }

    @ApiOperation(value = "根据token保存或者更新用户信息")
    @PostMapping("saveOrUpdateUserInfoByToken")
    public Results saveOrUpdateUserInfoByToken(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            UserInfo user = new UserInfo();
            user.setId(memberId);
            BeanUtils.copyProperties(userInfo, user);
            userInfoService.saveOrUpdate(user);
            String token = JwtUtils.getJwtToken(user.getId(), user.getNickname(),null);
            return Results.ok().data("token", token).message(MessageConstant.EDIT_USERINFO_SUCCESS);
        } catch (BeansException e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_USERINFO_FAIL);
        }
    }


    @ApiOperation(value = "根据id删除用户信息")
    @DeleteMapping("deleteUserById/{id}")
    public Results deleteUserById(@ApiParam(name = "id", value = "用户id", required = true)
                                  @PathVariable String id) {
        try {
            UserInfo user = userInfoService.getById(id);
            if (user != null) {
                userInfoService.removeById(id);
            }
            return Results.ok().message(MessageConstant.DELETE_USERINFO_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_USERINFO_FAIL);
        }
    }

    @ApiOperation(value = "根据用户id修改禁用")
    @PutMapping("updateDisableUserById/{id}")
    public Results updateDisableUserById(@ApiParam(name = "id", value = "用户id", required = true)
                                         @PathVariable String id) {
        try {
            UserInfo user = userInfoService.getById(id);
            if (user != null) {
                Boolean isDisable = user.getIsDisabled();
                isDisable = !isDisable;
                user.setIsDisabled(isDisable);
                userInfoService.updateById(user);
            }
            return Results.ok().message(MessageConstant.DISABLEDUSER_ERROR);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_USERINFO_FAIL);
        }
    }

    /*
    * 新增根据clubId查询用户信息
    * */
    @ApiOperation(value = "带条件分页查询用户")
    @PostMapping("getUserInfoByQueryVo/{page}/{limit}")
    public Results getUserInfoByQueryVo(@ApiParam(name = "page", value = "查询页数", required = true)
                                        @PathVariable Integer page, @ApiParam(name = "limit", value = "查询数量", required = true)
                                        @PathVariable Integer limit, @ApiParam(name = "queryVo", value = "查询条件", required = false)
                                        @RequestBody(required = false) UserInfoQueryVo queryVo) {
        try {
            Page<UserInfo> infoPage = new Page<>(page, limit);
            String nickname = queryVo.getNickname();
            Integer grade = queryVo.getGrade();
            String majorId = queryVo.getMajorId();
            String collegeId = queryVo.getCollegeId();
            Integer gender = queryVo.getGender();
            Boolean isDisabled = queryVo.getIsDisabled();
            String start = queryVo.getStart();
            String end = queryVo.getEnd();
            String clubId= queryVo.getClubId();

            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(clubId)) {
                wrapper.eq(UserInfo::getClubId, clubId);
            }
            if (!ObjectUtils.isEmpty(grade)) {
                wrapper.eq(UserInfo::getGrade, grade);
            }
            if (!StringUtils.isEmpty(majorId)) {
                wrapper.eq(UserInfo::getMajorId, majorId);
            }
            if (!StringUtils.isEmpty(collegeId)) {
                wrapper.eq(UserInfo::getCollegeId, collegeId);
            }
            if (!StringUtils.isEmpty(gender)) {
                wrapper.eq(UserInfo::getGender, gender);
            }
            if (!StringUtils.isEmpty(nickname)) {
                wrapper.like(UserInfo::getNickname, nickname);
            }
            if (!ObjectUtils.isEmpty(isDisabled)) {
                wrapper.eq(UserInfo::getIsDisabled, isDisabled);
            }
            if (!StringUtils.isEmpty(start)) {
                wrapper.ge(UserInfo::getGmtCreate, start);
            }
            if (!StringUtils.isEmpty(end)) {
                wrapper.le(UserInfo::getGmtCreate, end);
            }
            IPage<UserInfo> iPage = userInfoService.page(infoPage, wrapper);
            return Results.ok().data("list", iPage).message(MessageConstant.QUERY_USERINFO_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USERINFO_FAIL);
        }
    }

    @ApiOperation(value = "根据token修改用户密码")
    @PostMapping("updatePasswordByToken")
    public Results updatePasswordByToken(@RequestBody UserInfo userInfo, HttpServletRequest request) {

        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            UserInfo user = userInfoService.getById(memberId);
            String password = userInfo.getPassword();//用户传入的密码
            String oldPassword = user.getPassword();//旧密码md5
            String newPasswordMd5 = MD5.encrypt(password);//新密码md5
            //验证原密码是否正确，并且新密码不能与旧密码相同
            if (!StringUtils.isEmpty(password) && !newPasswordMd5.equals(oldPassword)) {

                user.setPassword(newPasswordMd5);
                userInfoService.updateById(user);
            } else {
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.VALIDAT_EQUALPWD_ERROR);
            }
            return Results.ok().message(MessageConstant.EDIT_USERINFO_SUCCESS);
        } catch (BaiYunException e) {
            throw e;

        }
    }

    @ApiOperation(value = "根据userId获取用户是否被禁用")
    @GetMapping("isDisabled/{userId}")
    public Results isDisabled(@PathVariable String userId) {
        try {
            String cacheKey = "userDisabledStatus:" + userId;
            Boolean isDisabled = (Boolean) redisTemplate.opsForValue().get(cacheKey);
            if (isDisabled == null) {
                UserInfo user = userInfoService.getById(userId);
                if (user == null) {
                    throw new BaiYunException(ResultCode.ERROR, MessageConstant.VALIDATEUSER_ERROR);
                }
                isDisabled = user.getIsDisabled();
                redisTemplate.opsForValue().set(cacheKey, isDisabled, 10, TimeUnit.MINUTES);
            }
            return Results.ok()
                    .message("该用户状态正常")
                    .data("isDisabled", isDisabled)
                    .message(MessageConstant.QUERY_USERINFO_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        }
    }


    // 获取是否为协会成员信息
    private Boolean isJoin(String userId) {
        try {
            JoinUserDept userDept = JSON.parseObject(JSON.toJSONString(joinClient.getDeptsByUserId(userId).getData().get("userDept")), JoinUserDept.class);
            if (userDept != null) {
                String deptId = userDept.getDeptId();
                if (!StringUtils.isEmpty(deptId)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USERINFO_FAIL);
        }
    }
}

